using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using Citrix.WorkflowStudio.Common;
using Citrix.WorkflowStudio.CustomActivities.Designers;
using Citrix.WorkflowStudio.CustomActivities.Editors;
using Citrix.WorkflowStudio.CustomActivities.Serializers;
using Citrix.WorkflowStudio.User;

namespace Citrix.WorkflowStudio.Activities.WFSIISActivites
{
	#region Attribute Definitions and Comments
	[Designer(typeof(BaseActivityDesigner))]
    [DisplayNameAttribute(@"Delete Application Pool")]
    [Description(@"This activity will delete an application pool on a given server and site.")]
	[ActivityTreePath(@"IIS/IIS7")]
	[ActivityValidator(typeof(IIS7DeleteApplicationPoolValidator))]
	[ToolboxBitmapAttribute(typeof(IIS7DeleteApplicationPool), @"Resources.IIS7DeleteApplicationPool16.png")]
	[BaseActivityDesigner(ImageResourceName = @"Resources.IIS7DeleteApplicationPool32.png", AssemblyType = typeof(IIS7DeleteApplicationPool))]
	#endregion Attribute Definitions and Comments

	public partial class IIS7DeleteApplicationPool : ActivityBase
	{
		#region Constructor
		public IIS7DeleteApplicationPool()
		{
			InitializeComponent();
		}
		#endregion Constructor

        public static DependencyProperty ApplicationPoolNameProperty = DependencyProperty.Register("ApplicationPoolName", typeof(String), typeof(IIS7DeleteApplicationPool));
        [DefaultValue("")]
        [Category(@"Application Pool Information")]
        [DisplayName(@"AppPool Name")]
        [Description(@"The application pool name that you want to delete.")]
        [Browsable(true)]
        [InputAttribute]
        [EditorAttribute(typeof(TextEditor), typeof(UITypeEditor))]
        public String ApplicationPoolName
        {
            get
            {
                return ((String)(base.GetValue(ApplicationPoolNameProperty)));
            }
            set
            {
                base.SetValue(ApplicationPoolNameProperty, value);
            }
        }


        public static DependencyProperty ServerNameProperty = DependencyProperty.Register("ServerName", typeof(String), typeof(IIS7DeleteApplicationPool));
        [DefaultValue("")]
        [Category(@"Application Pool Information")]
        [DisplayName(@"Server Name")]
        [Description(@"Enter the name of the server where you would like this action to happen. This can be either a name or IP address.")]
        [Browsable(true)]
        [InputAttribute]
        [EditorAttribute(typeof(TextEditor), typeof(UITypeEditor))]
        public String ServerName
        {
            get
            {
                return ((String)(base.GetValue(ServerNameProperty)));
            }
            set
            {
                base.SetValue(ServerNameProperty, value);
            }
        }

		// The logic for your activity belongs in the Execute method below
		#region Activity Execution Logic
		protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
		{
			// Expand all string properties with the required attribute
			ExpandStringProperties(executionContext.Activity);

			try
			{
                Microsoft.Web.Administration.ServerManager pServerManager = Microsoft.Web.Administration.ServerManager.OpenRemote(this.ServerName);

                Microsoft.Web.Administration.ApplicationPool pExistingApplicationPool = pServerManager.ApplicationPools[this.ApplicationPoolName];

                pServerManager.ApplicationPools.Remove(pExistingApplicationPool);

                pServerManager.CommitChanges();
			}

			catch (Exception e)
			{
				String errmsg = "An error has occurred. The error is \"" + e.Message.ToString() + "\"";

				if (e.InnerException != null && e.InnerException.ToString().Length > 0)
					errmsg += "\nAdditional error info: \"" + e.InnerException.ToString() + "\"";

				throw new Exception(errmsg);

				// NOTE: Do not set ActivityExecutionStatus to Faulting if you throw an exception manually.
			}

			// You need to conclude your Execute method by setting the ActivityExecutionStatus.
			// Valid values are:
			//	Canceling
			//	Closed
			//	Compensating
			//	Executing
			//	Faulting
			//	Initialized
			return ActivityExecutionStatus.Closed;
		}
		#endregion Activity Execution Logic
	}

	// Property validation code
	//     In the Validate method you have to create a new instance of the activity class above,
	//     create a new ValidationErrorCollection instance, and then write the code to process the validation.
	//     For each validation error/warning, you need to add the error/warning to the ValidationErrorCollection.
	//     Finally, the Validate method should return the ValidationErrorCollection object.
	#region Validation Logic
	public class IIS7DeleteApplicationPoolValidator : ActivityValidator
	{
		public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
		{
			IIS7DeleteApplicationPool MyActivity = obj as IIS7DeleteApplicationPool;
			ValidationErrorCollection errs = new ValidationErrorCollection();
            
			if ((MyActivity != null) && (MyActivity.Parent != null))
			{
                if (MyActivity.ServerName == null || MyActivity.ServerName.Length == 0)
                {
                    errs.Add(new ValidationError(@"You need to specify a server address where the application exists. Please set the 'Server Name' property", 101, false, @"ServerNameProperty"));
                }
                if (MyActivity.ApplicationPoolName == null || MyActivity.ApplicationPoolName.Length == 0)
                {
                    errs.Add(new ValidationError(@"You need to specify the application name to delete. Please set the 'Application Pool Name' property", 101, false, @"ApplicationPoolNameProperty"));
                }
            }
            
			#region StopOnError Validation
        	        if (!MyActivity.StopOnError)
	                {
        	            Boolean found = false;
	                    if (MyActivity.Activities != null)
        	            {
                	        for (int i = 0; ((i < MyActivity.Activities.Count) && (!found)); i++)
                        	{
	                            if (MyActivity.Activities[i].GetType() == typeof(System.Workflow.ComponentModel.FaultHandlersActivity))
        	                    {
                	                found = true;
                        	        CompositeActivity faultHandlers = (CompositeActivity)(MyActivity.Activities[i]);
                                	if ((faultHandlers.Activities == null) || (faultHandlers.Activities.Count == 0))
	                                    errs.Add(new ValidationError("The 'Stop On Error' property is set to 'false' but the auto-generated faultHandlerActivity has been manually deleted.", 101, false, "StopOnError"));
        	                    }
                	        }
                        	if (!found)
	                            errs.Add(new ValidationError("The 'Stop On Error' property is set to 'false' but the auto-generated faultHandlersActivity has been manually deleted.", 101, false, "StopOnError"));
        	            }
                	}
			#endregion StopOnError Validation

            
			// Return the ValidationErrorCollection
			return errs;
		}
	}
	#endregion Validation Logic
}
